const Router = require('koa-router')
const { check, catchError, generateOk } = require('../../lib/check')
const { addTab, hasOneTab, removeTab, editTab, getAllTabs, searchTab } = require('../../model/tab')

let tab = new Router()

tab.post('/add', async (ctx) => {
  try {
    const data = ctx.request.body
    const tabs = getAllTabs()
    check(!!data.value, 'Params_Lost')
    check(!!data.lable, 'Params_Lost')
    check(data.state !== undefined, 'Params_Lost')
    const findTab = searchTab(data.lable)
    check(!findTab, 'Tab_Has_Been_Exist')
    const hasValue = tabs.find(item => item.value === data.value)
    check(!hasValue, 'Value_Has_Been_Exist')
    addTab(data)
    ctx.body = generateOk({ tab: data })
  } catch (e) {
    catchError(e, ctx)
  }
})

tab.post('/changeState', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!data.value, 'Params_Lost')
    check(!!data.lable, 'Params_Lost')
    // check(data.state !== undefined, 'Params_Lost')
    const findTab = searchTab(data.lable)
    check(findTab, 'Not_Tab')
    editTab({ ...data, state: !data.state })
    ctx.body = generateOk({ tab: { ...data, state: !data.state } })
  } catch (e) {
    catchError(e, ctx)
  }
})

tab.post('/editValue', async (ctx) => {
  try {
    const data = ctx.request.body
    const tabs = getAllTabs()
    check(!!data.value, 'Params_Lost')
    check(!!data.lable, 'Params_Lost')
    const findTab = searchTab(data.lable)
    check(findTab, 'Not_Tab')
    const hasValue = tabs.find(item => item.value === data.value)
    check(!hasValue, 'Value_Has_Been_Exist')
    editTab(data)
    ctx.body = generateOk(data)
  } catch (e) {
    catchError(e, ctx)
  }
})

tab.post('/delete', async (ctx) => {
  try {
    const data = ctx.request.body
    check(data.value, 'Params_Lost')
    check(data.lable, 'Params_Lost')
    check(data.state !== undefined, 'Params_Lost')
    const findTab = searchTab(data.lable)
    check(findTab, 'Not_Tab')
    check(findTab.value === data.value && findTab.lable === data.lable, 'Wrong_Tab')
    removeTab(data)
    ctx.body = generateOk(data)
  } catch (e) {
    catchError(e, ctx)
  }
})

tab.post('/get', async (ctx) => {
  try {
    const data = ctx.request.body
    const tabs = getAllTabs()
    let newTabs = tabs
    if (data.state !== undefined) {
      newTabs = newTabs.filter((item) => item.state === data.state)
    }
    if (!!data.lable) {
      newTabs = newTabs.filter(item => item.lable.includes(data.lable))
    }
    const start = data.offset === undefined ? 0 : data.offset
    const size = data.limit === undefined ? 7 : data.limit
    const resData = newTabs.slice(start, start + size)
    ctx.body = generateOk({ data: resData, total: newTabs.length, length: resData.length })
  } catch (e) {
    catchError(e, ctx)
  }
})


module.exports = tab